/*! Index Buffer Direct3D 11 Implementation

@author Sergio J. de los Santos
*/
#include <stdafx.h>

#include "ConstantBuffers.h"


/*! Constructor

@param pd3dDevice	Direct3D 11 Device
*/
IndexBufferD3D11::IndexBufferD3D11(ID3D11Device* pd3dDevice)
{
	//m_spStateManager	= spStateManager;
	m_pd3dDevice		= pd3dDevice;
	m_pIB				= NULL;
}

//! Destructor
IndexBufferD3D11::~IndexBufferD3D11( )
{
	Destroy();
}



//! Invalida al IB, liberando sus objetos atributos
void IndexBufferD3D11::Destroy()
{
	_SAFE_RELEASE( m_pIB );
}


/*! Create the index buffer

@param ibDesc	Index Buffer Descriptor
@param pIndices	Indices para inicializasr el Index Buffer (es necesario si es inmutable, sino es opcional)
@returns true si finalizo correctamente, sino false
*/
bool IndexBufferD3D11::Create(const IBDescriptor& ibDesc, const void* pIndices)
{
	m_ibDescriptor = ibDesc;
	// Si no hay indices!
	if( m_ibDescriptor.GetIndexCount() == 0 )	return false;
	// Si no hay Dispositivo D3D
	if(!m_pd3dDevice)	return false;

	D3D11_BUFFER_DESC bufferDesc;
	bufferDesc.Usage			= D3D11_USAGE_IMMUTABLE;
	bufferDesc.ByteWidth		= m_ibDescriptor.GetIndexSize() * m_ibDescriptor.GetIndexCount();
	bufferDesc.BindFlags		= D3D11_BIND_INDEX_BUFFER;
	bufferDesc.CPUAccessFlags	= 0;
	bufferDesc.MiscFlags		= 0;

	D3D11_SUBRESOURCE_DATA InitData;
	InitData.pSysMem = pIndices;
	InitData.SysMemPitch = 0;
	InitData.SysMemSlicePitch = 0;

	m_dxgiFormat = (m_ibDescriptor.GetIndexSize() == 2)? DXGI_FORMAT_R16_UINT: DXGI_FORMAT_R32_UINT;

	HRESULT hr = m_pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &m_pIB );
	if( FAILED( hr ) )
		return false;

#ifdef DEBUG
	const char szName[] = "IndexBuffer";
	m_pIB->SetPrivateData( WKPDID_D3DDebugObjectName, sizeof( szName ) - 1, szName );
#endif 


	m_pIB->GetDesc(&m_descBuffer);

	return true;
}
